// pages/login/login.js
import {
  signIn
} from '../../api/login'
import {
  NICKNAME,
  USER_ID,
  COIN_COUNT
} from '../../constant/constant'
const app = getApp()
Page({

  /**
   * Page initial data
   */
  data: {
    allowLogin: false,
    username: '',
    password: ''

  },
  userNameInput: function (e) {
    this.setData({
      username: e.detail.value
    })
    this.checkAllowLogin()
  },
  passwordInput: function (e) {
    this.setData({
      password: e.detail.value
    })
    this.checkAllowLogin()
  },
  login: function () {
    const {
      username,
      password
    } = this.data
    signIn(username, password).then((res) => {
      console.log('res', res)
      if (res) {
        let d = res.data
        wx.setStorageSync(NICKNAME, d.nickname)
        wx.setStorageSync(COIN_COUNT, d.coinCount)
        wx.setStorageSync(USER_ID, d.id)
        app.globalData.hasLogined = true
        wx.navigateBack({
          delta: 1,
          success:function(res){
            console.log('xxx',res)
          }
        })
      }
    })
  },
  goRegister: function () {
    wx.navigateTo({
      url: '../register/register',
    })
  },
  checkAllowLogin() {
    const {
      username,
      password
    } = this.data
    if (username.length > 0 && password.length > 0) {
      this.setData({
        allowLogin: true
      })
    } else {
      this.setData({
        allowLogin: false
      })
    }
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function (options) {

  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function () {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function () {

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function () {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function () {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function () {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom: function () {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage: function () {

  }
})